var gulp    = require('gulp');
var concat 	= require('gulp-concat');
var uglify 	= require('gulp-uglify');
var rename 	= require('gulp-rename');
var config  = require('../config').scripts;
var bundleLogger = require('../util/bundleLogger');
var plumber = require('gulp-plumber');
var handleErrors = require('../util/handleErrors2');

gulp.task('scripts', function(callback) {
	var bundleQueue = config.bundleConfigs.length;

	var scriptThis = function(bundleConfig){
		// Log when bundling starts
      	bundleLogger.start(bundleConfig.outputName);

	    var reportFinished = function() {  
	      	// Log when bundling completes
	      	bundleLogger.end(bundleConfig.outputName)

	      	if(bundleQueue) {
	        	bundleQueue--;
	        	if(bundleQueue === 0) {
	          		callback();
	    		}
	      	}
	    };

		return gulp.src(bundleConfig.src)
			.pipe(plumber({errorHandler: handleErrors}))
			.pipe(concat(bundleConfig.outputName))
			.pipe(gulp.dest(bundleConfig.dest))
			.pipe(rename({ extname: '.min.js' }))
			.pipe(uglify())
			.pipe(gulp.dest(bundleConfig.dest))
			.on('end', reportFinished);
	}

	config.bundleConfigs.forEach(scriptThis);

});
